package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import uit.edu.vn.Model.mySMS;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.SMSListAdapter;
import uit.edu.vn.Utility.httpUploader;
import uit.edu.vn.Utility.xStreamXML;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class SMSBackupActivity extends MyActivity{
	private Cursor myCursor;

    private ContentResolver cr; 
	private ListView listview;
	private List<mySMS> listSms = new ArrayList<mySMS>();
	private ArrayList<mySMS> itemSMSCheck=new  ArrayList<mySMS>(); 
//	private String urlString = "http://"+ LoginActivity.getIPAddress()+"/ServerWeb/UploadServlet.jsp";
	private String columns[] = new String[] { People.NAME, People.NUMBER };
	private int numberOfItemSelected = 0;
	private Context context;
	private ProgressDialog loadingSMSDialog;
	private SMSListAdapter mAdapter ;
    private AlertDialog.Builder dialog;
    private EditText edt_Name;
    private TextView titleHeader;
    private Uri mInboxURI; 
    private String smsName ;
    private String smsBody ;
    private String smsDate ;
    private long smsId;
    private long smsThreadId;
    private String smsProtocol;
    private String smsType;
    private String smsNumber;
    private String defaultName;
    private File smsBackup;
    private AESControl aes;
    private int smsFileType = 2;
    private String urlString = null;
    private String userid = null;
    private String username = null;
    private String password = null;
    private String path=Environment.getExternalStorageDirectory()+"/BackupManager/SMS";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp"; 
		setContentView(R.layout.backup_file);
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(SMSBackupActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }	
	      System.out.println("SMSBackupActivity");
	      System.out.println("username: "+ username);
	      System.out.println("password: "+ password);
	      System.out.println("userid:   "+ userid);
	      System.out.println("address:   "+ urlString);
		File dir = new File(path);
		dir.mkdirs();
		listview =(ListView)findViewById(R.id.listFileBackup);
	    listview.setChoiceMode(2);
	    titleHeader=(TextView)findViewById(R.id.txt_titleFile);
		titleHeader.setText(R.string.title_BackupHeaderSMS);
	    context=getBaseContext();
	    // xu ly dialog yeu cau nhap ten 
	    dialog = new AlertDialog.Builder(this);
        edt_Name= new EditText(this);
        edt_Name.setSingleLine();
        dialog.setView(edt_Name);
	    //goi Dialog
        loadingSMSDialog= new ProgressDialog(this);
        loadingSMSDialog.setMessage(getResources().getString(R.string.dialog_message_progress));
        loadingSMSDialog.setCancelable(false);
        loadingSMSDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
     

	    new BackGroundTask().execute();
	    listview.setOnItemClickListener(new OnItemClickListener() {
	    	@Override
	    	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
	    			long arg3) {
	    		// TODO Auto-generated method stub
	    		showToast("dang mo tin nhan ");
	    		Intent intent = new Intent(Intent.ACTION_MAIN);
	    	    intent.setData(Uri.parse("content://mms-sms/inbox/"+listSms.get(arg2).getThreadID()));	    	    
	    		startActivity(intent);
	    	}
		});
	}
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	} 		
	
	//theard xu ly chinh
	private class BackGroundTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute() 
		{
		// TODO Auto-generated method stub
		super.onPreExecute();
		loadingSMSDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			doInBackGround();
			return null;
		}
		@Override
		protected void onPostExecute(Void result)
		{
		// TODO Auto-generated method stub
			mAdapter= new SMSListAdapter(context,listSms);
		    listview.setAdapter(mAdapter); 
		    myCursor.close();
		     //unload dialog
		    loadingSMSDialog.dismiss();
		super.onPostExecute(result);
		}
	}
	private void doInBackGround()
	{
		cr=getContentResolver();
		mInboxURI= Uri.parse("content://sms/inbox"); 
		myCursor=cr.query(mInboxURI, null, null, null, null);
		startManagingCursor(myCursor);

		while(myCursor.moveToNext())
        {
			 
			  smsNumber = myCursor.getString(myCursor.getColumnIndexOrThrow("address"));
              smsId=myCursor.getLong(myCursor.getColumnIndexOrThrow("_id"));
              smsThreadId=myCursor.getLong(myCursor.getColumnIndexOrThrow("thread_id"));
              smsProtocol=myCursor.getString(myCursor.getColumnIndexOrThrow("protocol"));
              smsType=myCursor.getString(myCursor.getColumnIndexOrThrow("type"));
              smsBody =myCursor.getString(myCursor.getColumnIndexOrThrow("body"));
              //goi ham tim kiem name;
              smsName=lookingContact(smsNumber);
              if(smsName==null)
              {
            	  smsName=smsNumber;
              }
              try {
            	  //chuyen milisecond sang ngay
                  String date=myCursor.getString(myCursor.getColumnIndexOrThrow("date"));
                  long currentDay = Long.parseLong(date);
                  Date dateFromSms = new Date(currentDay);
                  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
                  smsDate= formatter.format(dateFromSms);

                  listSms.add(new mySMS(smsId,smsThreadId,smsName,smsNumber, smsBody,smsDate,currentDay,smsProtocol,smsType));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

        }
	}
	//------------------------- xu ly option menu ------------------------------------
	 public boolean onCreateOptionsMenu(Menu menu) 
	 {
	    	// TODO Auto-generated method stub
	    	//return super.onCreateOptionsMenu(menu);
	    	new MenuInflater(getApplicationContext()).inflate(R.menu.backup_sms_option_menu, menu);
		    return super.onCreateOptionsMenu(menu);
	 }
	 @Override
	 public boolean onMenuOpened(int featureId, Menu menu) {
		// TODO Auto-generated method stub
		 if(numberOfItemSelected==listSms.size())
	  	   {
	  		   menu.findItem(R.id.menu_backup_SMSSelectAll).setTitle(getResources().getString(R.string.txt_uncheckall));
	  	   }
	  	   else
	  	   {
	  		   menu.findItem(R.id.menu_backup_SMSSelectAll).setTitle(getResources().getString(R.string.txt_checkall));
	  		      
	  	   }
	    	
		return super.onMenuOpened(featureId, menu);
	 }
	
	    @Override
	 public boolean onOptionsItemSelected(MenuItem item) 
	 {
	    	// TODO Auto-generated method stub
	    switch(item.getItemId())
	    {
	    	case R.id.menu_backup_SMSToSDCard:
	    			// xu ly chon file check
	    			//neu flag =1 thì đã có sms check roi 
	    			//flag=0 nghia là chưa có chon sms nao
	    			int flag=0;
	    			for(int i=0;i<listSms.size();i++)
	    			{
	    				if(listSms.get(i).getChecked()==true)
	    				{
	    					flag=1;
	    					numberOfItemSelected++;
	    				}
	    				
	    			}
	    			if(flag==0)
	    			{
	    				numberOfItemSelected=0;
	    			}
	    			//xu ly chon file backup
	    			if(listSms.isEmpty())
	    			{
	    				showToast("list trong");
	    			}
	    			else 
	    			{
	    				if(numberOfItemSelected==0)
	    				{
	    					showToast("Vui lòng chon tin nhắn cần sao lưu");
	    				}
	    				else
	    				{
	    					// xu ly dat ten file
	    					 defaultName = "Sms_backup("+MyActivity.getDateTime()+")";
	    					//final String fileName="";
	    					final File root= Environment.getExternalStorageDirectory();
	    					edt_Name.setText(defaultName);
	    					showNameFileDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_tentaptin), new OnClickListener() 
	    					{	    						
								@Override
								public void onClick(DialogInterface dialog, int which) 
								{
									// TODO Auto-generated method stub									
									String fileName= edt_Name.getText().toString().trim();
									fileName+=".sbk";
									if(checkName(fileName)){										
										//tao duong dan toi file
				    					File temp = new File(root.getAbsolutePath()+"/BackupManager/SMS");
				    					temp.mkdirs();
				    					if(root.canWrite()){			    					
				    					//	final File smsBackup= new File(temp, fileName);
				    						 smsBackup= new File(temp, fileName);
				    						if(smsBackup.exists())
				    						{//kiem tra neu ton tai file thi xuat dialog hoi ghi de ko 
				    							showConfirmDialog(getResources().getString(R.string.dialog_canhbao), getResources().getString(R.string.dialog_message_ghide), new OnClickListener() {
													
													@Override
													public void onClick(DialogInterface dialog, int which) 
													{
														// TODO Auto-generated method stub
														itemSMSCheck.clear();
														for(int i=0;i<listSms.size();i++)
									    				{
									    					if(listSms.get(i).getChecked()==true)
									    					{
									    						mySMS entry = listSms.get(i);
									    						itemSMSCheck.add(entry);
									    					}
									    				}
														new BackupSdcardTask().execute();
													//	backupSmsToSDcard(itemSMSCheck, smsBackup);
											
													}
												});
				    						}
				    						else
				    						{// khong co file trung ,sao luu sms
				    							itemSMSCheck.clear();
												for(int i=0;i<listSms.size();i++)
							    				{
							    					if(listSms.get(i).getChecked()==true)
							    					{
							    						mySMS entry = listSms.get(i);
							    						itemSMSCheck.add(entry);
							    					}
							    				}
												new BackupSdcardTask().execute();
												
				    						}	
				    					}
				    					else{
				    						showToast("Không thể ghi len sdcard");
				    					}
									}else
										showToast("Tên tập tin không hợp lệ");			    					
//			    					duyet mang và set check lai false
									for(int i=0;i<listSms.size();i++){
										listSms.get(i).setChecked(false);
									}
									mAdapter.notifyDataSetChanged();			    					
								}
	    					});
	    				}	    			
	    		}
	    		return true;
	    	case R.id.menu_backup_SMSToServer:
	    		// xu ly chon file check
    			//neu flag =1 thì đã có sms check roi 
    			//flag=0 nghia là chưa có chon sms nao
    				int flag2=0;
    				for(int i=0;i<listSms.size();i++)
    				{
    					if(listSms.get(i).getChecked()==true)
    					{
    						flag2=1;
    						numberOfItemSelected++;
    					}
    				
    				}
    				if(flag2==0)
    				{
    					numberOfItemSelected=0;
    				}
    		
	    			//xu ly chon file backup
	    			if(listSms.isEmpty())
	    			{
	    				showToast("list trong");
	    			}
	    			else 
	    			{
	    				Log.d("list", "list co du lieu ");
	    				if(numberOfItemSelected==0)
	    				{
	    					showToast("Vui lòng chọn tin nhắn cần sao lưu");
	    				}
	    				else
	    				{
	    					File root= Environment.getExternalStorageDirectory();
	    					String pathFile=root.getAbsolutePath()+"/BackupManager/SMS";
	    					//tao duong dan toi file
	    					File temp = new File(pathFile);
	    					temp.mkdirs();
	    					if(root.canWrite())
	    					{
	    						final String fileName = "sms_backup("+MyActivity.getDateTime()+").sbk";
	    						smsBackup= new File(pathFile, fileName);
	    						Log.d("name file", fileName);
	    						if(smsBackup.exists())
	    						{//kiem tra neu ton tai file thi xuat dialog hoi ghi de ko 
	    							showConfirmDialog(getResources().getString(R.string.dialog_canhbao),getResources().getString(R.string.dialog_message_ghide), new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) 
									{
										// TODO Auto-generated method stub
										itemSMSCheck.clear();
										for(int i=0;i<listSms.size();i++)
					    				{
					    					if(listSms.get(i).getChecked()==true)
					    					{
					    						mySMS entry = listSms.get(i);
					    						itemSMSCheck.add(entry);
					    					}
					    				}
										backupSmsToServer(itemSMSCheck, smsBackup);
										mAdapter.notifyDataSetChanged();
									}
	    							});
	    						}
	    						else
	    						{
	    							//sao luu len server
	    							Log.d("tag", " server");
	    							showConfirmDialog(getResources().getString(R.string.dialog_thongbao), "Bạn muốn lưu tin nhắn này lên Server", new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) 
										{
											//check ketnoi internet 
											CheckInternet chkI= new CheckInternet(context);
											 if(chkI.checkStatus().equals(true))
												{

												 new BackupServerTask().execute();
										    
											
					//						
										}
										
								        else
								        {
								        	Log.d("ketnoi", "ko co ket noi internet");
								        	showToast("Không có kết nối");
								        
								        }
										}
									});

	    						}	
	    					}
	    					else
	    					{
	    						showToast("Không thể ghi len Server");
	    					}
	    				
	    				}
	    			}	
	    			return true;
	    			
	    	case R.id.menu_backup_SMSLogout:
	    			logOut();
	    			Intent intent = new Intent(SMSBackupActivity.this, LoginActivity.class);
	    			startActivity(intent);
	    			this.finish();
	    			return true;
	    	
	    	case R.id.menu_backup_SMSDelete:
	    			//duyet mang sms check neu chua check thi yeu cau check
	    			//neu da co check lay id vi tri check va goi ham deletesmsbyid
	    			// xong refresh lai adapter 
	    			//neu flag =1 thì đã có sms check roi 
    				//flag=0 nghia là chưa có chon sms nao
    				int flag1=0;
    				for(int i=0;i<listSms.size();i++)
    				{
    					if(listSms.get(i).getChecked()==true)
    					{
    						flag1=1;
    						numberOfItemSelected++;
    					}
    				
    				}
    				if(flag1==0)
    				{
    					numberOfItemSelected=0;
    				}
	    			if(numberOfItemSelected==0)
	    			{
	    				showToast("Vui lòng chọn tin nhắn cần xóa");
	    			}
	    			else
	    			{
	    				
	    				showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_xoa), new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								new AsyncTask<Void, Void, Void>()
								{
									protected void onPreExecute() 
									{
										loadingSMSDialog.setMessage("Đang xóa tin nhắn");
										loadingSMSDialog.show();
									};
								
									@Override
									protected Void doInBackground(
											Void... params) {
										// TODO Auto-generated method stub
										for(int i=0;i<listSms.size();i++)
										{
											if(listSms.get(i).getChecked()==true)
											{
												if(deleteSMSByID(listSms.get(i).getID())==true);
												//Log.d("tag",String.valueOf(j));
												{	
													listSms.remove(i);
												
													i--;
													numberOfItemSelected--;
											
												}
											}
										}
										return null;
									}
									@Override
									protected void onPostExecute(Void result) {
										// TODO Auto-generated method stub
										super.onPostExecute(result);
										mAdapter.notifyDataSetChanged();
										loadingSMSDialog.dismiss();
										showAlertDialog(getResources().getString(R.string.dialog_thongbao), "Xóa thành công ", new OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												dialog.cancel();
											}
										});
						
									}
								}.execute();
								
							}
						});
	    			}
	    			
	    			return true;
	    	case R.id.menu_backup_SMSSelectAll:
	    		//bien numberof dung de kiem tra 
	    		if(numberOfItemSelected==listSms.size())
    			{
    				// xu ly bo chon
    				for(int i=0;i<listSms.size();i++)
    				{
    					listSms.get(i).setChecked(false);
    				
    				}
    				numberOfItemSelected=0;
    			}
    			else
    			{
    				// xu ly chon
    				for(int i=0;i<listSms.size();i++)
    				{	
    					listSms.get(i).setChecked(true);
    				}
    				numberOfItemSelected=listSms.size();
    			}
    				mAdapter.notifyDataSetChanged();
    			return true;
	    }
	    return false;
	    }
	  //--------------------------Task back up ---------------------------------
	   private class BackupServerTask extends AsyncTask<Void, Void, Void>
	   {
		   @Override
		   protected void onPreExecute() 
		   {
			   // TODO Auto-generated method stub
			   super.onPreExecute();
			   loadingSMSDialog.setMessage(getResources().getString(R.string.dialog_message_progress_up_server));
			   loadingSMSDialog.show();
		   }
		   @Override
		   protected Void doInBackground(Void... params) 
		   {
			   // TODO Auto-generated method stub
				//sao luu sms
				itemSMSCheck.clear();
				for(int i=0;i<listSms.size();i++)
				{
					if(listSms.get(i).getChecked()==true)
					{
						mySMS entry = listSms.get(i);
						itemSMSCheck.add(entry);
					}
				}
				backupSmsToServer(itemSMSCheck, smsBackup);
			   return null;
		   }
		   @Override
		   protected void onPostExecute(Void result) 
		   {
			   // TODO Auto-generated method stub
				loadingSMSDialog.dismiss();
				for(int i=0;i<listSms.size();i++)
				{
					listSms.get(i).setChecked(false);
				}
				mAdapter.notifyDataSetChanged();
				showAlertDialog(getResources().getString(R.string.dialog_thongbao), " Tin nhắn "+smsBackup.getName()+" \n đã được sao lưu lên  máy chủ", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

			   super.onPostExecute(result);
		   }
	   }
	   private class BackupSdcardTask extends AsyncTask<Void, Void, Void>
	   {
		   @Override
		   protected void onPreExecute() 
		   {
			   // TODO Auto-generated method stub
			   super.onPreExecute();
			   loadingSMSDialog.show();
			   loadingSMSDialog.setMessage(getResources().getString(R.string.dialog_message_progress_sdcard));
		   }
		   @Override
		   protected Void doInBackground(Void... params) 
		   {
			   // TODO Auto-generated method stub
	
			
				backupSmsToSDcard(itemSMSCheck, smsBackup);
			   return null;
		   }
		   @Override
		   protected void onPostExecute(Void result) 
		   {
			   // TODO Auto-generated method stub
				loadingSMSDialog.dismiss();
				for(int i=0;i<listSms.size();i++)
				{
					listSms.get(i).setChecked(false);
				}
				mAdapter.notifyDataSetChanged();
				showAlertDialog(getResources().getString(R.string.dialog_thongbao), " Tin nhắn "+smsBackup.getName()+" \n đã được sao lưu thành công", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
						for(int i=0;i<listSms.size();i++)
						{
							listSms.get(i).setChecked(false);
						}
					}
				});

			   super.onPostExecute(result);
		   }
	   }
	  //-----------------cac ham lien quan khac----------------------------------
		public String lookingContact(String number)
		{
			ContentResolver localContentResolver = this.context.getContentResolver();
			Cursor findNameCursor =   localContentResolver.query(
			            Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,  Uri.encode(number)),  new String[] {PhoneLookup.DISPLAY_NAME}, 
			            null, 
			            null, 
			            null);
		    String contactName=null;
			try {
				while(findNameCursor.moveToNext()){
				    contactName = findNameCursor.getString(findNameCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
				  System.out.print( contactName);
				    }
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			finally {
				findNameCursor.close();

				}
			return contactName;
		}
		
	    private void backupSmsToSDcard(ArrayList<mySMS> smsbackup, final File exportFile) 
	    {
	    	try {
				FileOutputStream fos = new FileOutputStream(exportFile);
				OutputStreamWriter osw= new OutputStreamWriter(fos);
				String xml= xStreamXML.smsToXML(smsbackup);
				osw.write(xml);
				osw.flush();
				osw.close();				
			} catch (Exception e) {
				// TODO: handle exception
			//	Log.d("tag", e.getMessage());
				//throw new Exception(e.toString());

				
			}
	    }    
	    private void backupSmsToServer(ArrayList<mySMS> smsbackup, File exportFile)
	    {
	    	//thuc hien ghi du lieu
	    	Log.d("tao file", "backup file ");
	    	try {
	    		//ghi ra file tam roi goi httpupload để up , xong xóa file tam đi
	    		String fileName= exportFile.getName();
				FileOutputStream fos= new FileOutputStream(exportFile);
				OutputStreamWriter osw= new OutputStreamWriter(fos);
				String xml= xStreamXML.smsToXML(smsbackup);
				osw.write(xml);
				osw.flush();
				osw.close();
				Log.v("tag",exportFile.getPath());
			// thuc thi mã hóa tập tin
				aes= new AESControl(username);
				String output = exportFile.getPath()+".aes";
				Log.v("tag",output);
				aes.EncFile(exportFile.getPath(), output);
				FileInputStream fis= new FileInputStream(output);
				File encryptFile= new File(output);
                String temp = String.valueOf(userid)+"@"+String.valueOf(smsFileType)+"@"+"sao luu tin nhan len may chu!";
				httpUploader up= new httpUploader(urlString, temp, fileName);
				Log.d("file tam", "Xóa file tạm ");
				exportFile.delete();
				encryptFile.delete();
				System.out.println("chuoi tra ve la: "+up.doStart(fis));
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
	    }
	    public Boolean deleteSMSByID(long id)
	    {	
	    	try {
	    		Uri uri=Uri.parse("content://sms/");
		    	
		    	context.getContentResolver().delete(uri,"_id ="+String.valueOf( id),null);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return true;	    		    	
	    }
    	private boolean checkName(String name) {
    		return name.matches("([a-zA-Z0-9_\\-\\.()]+)");
    	}
	    public AlertDialog showNameFileDialog(String title, String msg, OnClickListener yesClick)
	    {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.ic_error);
			edt_Name= new EditText(this);
		    edt_Name.setSingleLine();
		    edt_Name.setText(defaultName);
		    builder.setView(edt_Name);
			if(title!=null) builder.setTitle(title);
			if(msg!=null) builder.setMessage(msg);
			return builder.setPositiveButton("Đồng ý ", yesClick).setNegativeButton("Hủy bỏ", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
		}
	    @Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	// TODO Auto-generated method stub
	    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
	    	{
	    		
						finish();
					
	    	}
	    	return super.onKeyDown(keyCode, event);
	    }
	   
}
